package com.test.socket;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class CompressClient {
	
	public static final int BUFSIZE =256;//size of read buffer
	public static void main(String[] args)throws IOException{
		InetAddress add = InetAddress.getLocalHost();//server ip address
		int port =8086;//server port
		String filename = "people.xml"; //file to read data from
		
		//open input and output file(name input.gz)
		FileInputStream fileIn = new FileInputStream(filename);
		FileOutputStream fileOut = new FileOutputStream(filename+".gz");
		
		//create socket connected to server on specified port
		Socket sock = new Socket(add, port);
		//send uncompressed byte stream to server
		sendBytes(sock, fileIn);
		//receive compressed byte stream from server
		InputStream sockIn =sock.getInputStream();
		int bytesRead; //number of bytes read
		byte[] buffer = new byte[BUFSIZE];//Byte buffer
		while((bytesRead=sockIn.read(buffer))!=-1){
			fileOut.write(buffer, 0, bytesRead);
			System.out.print("R");//reading progress indicator
		}
		System.out.println();//End progress indicator line
		sock.close();//close the socket and its stream
		fileIn.close();//close file streams
		fileOut.close();
	}
	
	private static void sendBytes(Socket sock,InputStream fileIn)throws IOException{
		OutputStream sockOut = sock.getOutputStream();
		int bytesRead; //number of bytes read
		byte[] buffer = new byte[BUFSIZE];//byte buffer
		while((bytesRead=fileIn.read(buffer))!=-1){
			sockOut.write(buffer,0,bytesRead);
			System.out.println("W");//writing progress indicator
			
		}
		sock.shutdownOutput();//Finished sending
	}
}
